/**
 * 功能:TK_SEND_BILLS 控制器类
 * 开发人员:yaren
 * 创建时间:2012/4/22 12:34:13
 */
package com.towker.frame.controller.warehouse;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.towker.core.page.PageModel;
import com.towker.core.page.PageNav;
import com.towker.core.util.CollectionUtil;
import com.towker.core.util.RefGoodsType;
import com.towker.frame.controller.BaseController;
import com.towker.frame.model.basicData.Customs;
import com.towker.frame.model.basicData.Goods;
import com.towker.frame.model.sell.Delivery;
import com.towker.frame.model.sell.RefGoods;
import com.towker.frame.model.warehouse.InWarehouse;
import com.towker.frame.model.warehouse.SendBills;
import com.towker.frame.model.warehouse.WarehouseAccounts;
import com.towker.frame.service.basicData.CustomsService;
import com.towker.frame.service.basicData.DepartmentsService;
import com.towker.frame.service.basicData.DepotsService;
import com.towker.frame.service.basicData.GoodsService;
import com.towker.frame.service.basicData.PersonService;
import com.towker.frame.service.basicData.SurplusOrderService;
import com.towker.frame.service.basicData.VehicleService;
import com.towker.frame.service.sell.ConsignmentService;
import com.towker.frame.service.sell.DeliveryService;
import com.towker.frame.service.sell.InvoiceAttachmentService;
import com.towker.frame.service.warehouse.SendBillsService;
import com.towker.frame.service.warehouse.WarehouseAccountsService;
import com.towker.frame.share.sys.user.UserShare;
import com.towker.web.MyRequest;

//TK_SEND_BILLS
@Controller
@SuppressWarnings("unchecked")
@RequestMapping("/manage/warehouse")
public class SendBillsController extends BaseController
{
	private SendBillsService service;
	private CustomsService customsService;//客户信息
	private DepartmentsService departmentsService;//部门信息
	private DepotsService depotsService;//仓库信息
	private GoodsService goodsService;//物品信息
	private WarehouseAccountsService warehouseAccountsService;
	private InvoiceAttachmentService invoiceAttachmentService;
	private ConsignmentService consignmentService;
	private DeliveryService deliveryService;
	private SurplusOrderService surplusOrderService;
	private PersonService personService;
	private VehicleService vehicleService;

	//业务对象注入
	public void setSendBillsService(SendBillsService service)
	{
		this.service = service;
	}
	
	public void setCustomsService(CustomsService customsService)
	{
		this.customsService = customsService;
	}
	
	public void setDepartmentsService(DepartmentsService departmentsService)
	{
		this.departmentsService = departmentsService;
	}
	
	public void setDepotsService(DepotsService depotsService)
	{
		this.depotsService = depotsService;
	}
	
	public void setGoodsService(GoodsService goodsService)
	{
		this.goodsService = goodsService;
	}
	
	public void setWarehouseAccountsService(WarehouseAccountsService warehouseAccountsService)
	{
		this.warehouseAccountsService = warehouseAccountsService;
	}
	
	public void setInvoiceAttachmentService(InvoiceAttachmentService invoiceAttachmentService)
	{
		this.invoiceAttachmentService = invoiceAttachmentService;
	}
	
	public void setConsignmentService(ConsignmentService consignmentService)
	{
		this.consignmentService = consignmentService;
	}
	
	public void setDeliveryService(DeliveryService deliveryService)
	{
		this.deliveryService = deliveryService;
	}

	public void setSurplusOrderService(SurplusOrderService surplusOrderService) {
		this.surplusOrderService = surplusOrderService;
	}
	
	public void setPersonService(PersonService personService)
	{
		this.personService = personService;
	}
	
	public void setVehicleService(VehicleService vehicleService)
	{
		this.vehicleService = vehicleService;
	}

	//添加
	@RequestMapping("/addSendBills{viewName}")
	public ModelAndView addSendBills(HttpServletResponse response, HttpServletRequest request, SendBills po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		if ("1".equals(viewName))
		{
			result = new ModelAndView();
			Map map = new HashMap();
			List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			List<Customs> customCodes= customsService.getList(map );
			List personList = personService.getList(map);  //人员信息
			List vehicleList = vehicleService.getList(map); //车辆信息
			result.addObject("personList",personList);
			result.addObject("vehicleList",vehicleList);
			result.addObject("customCodes", customCodes);
			result.addObject("departList", departList);
			result.addObject("deportList", deportList);
			result.addObject("send_sn",service.getNewSendSn());//发货单号
			result.addObject("sell_dep_code", UserShare.getCurrentUserDepCode(request));
			result.setViewName("/manage/warehouse/addSendBills.jsp");
		}
		else if ("2".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			MyRequest myRequest = new MyRequest(request);
			String goodsInfo = myRequest.getString("goodsInfo");
			
			po.setAuthCoCode(UserShare.getCurrentUserCoCode(request));
			//po.setAuthDepCode(UserShare.getCurrentUserDepCode(request));
			
			try
			{
				service.add(po);
				processRefGoods(request, RefGoodsType.SENDBILL_GOODS, po.getId(), goodsInfo);
				//处理库存量数量
				List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.SENDBILL_GOODS.getValue(),po.getId() );
				
				calcGoodsStock(new ArrayList<RefGoods>(), refGoods, surplusOrderService, po.getDepot_code(), po.getAuthCoCode(), false, true);
				
				writer.write("添加发货单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("添加发货单失败！" + e.getCause());
			}
		}
		return result;
	}

	//删除
	@RequestMapping("/delSendBills")
	public void delSendBills(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		MyRequest req = new MyRequest(request);
		long[] ids = req.getLongArray("keyIndex", 0);
		
		for (Long id : ids) {
			SendBills w = service.getById(id);
			if (w != null) {
				List<RefGoods> refOldGoods = refGoodsService.getByInfoType(RefGoodsType.SENDBILL_GOODS.getValue(), id.intValue());
				calcGoodsStock(refOldGoods, new ArrayList<RefGoods>(), surplusOrderService, w.getDepot_code(), w.getAuthCoCode(), true, true);
			}
		}
		service.delByIds(CollectionUtil.toLongArray(ids));
		response.sendRedirect(req.getRefererURL());
	}

	//修改
	@RequestMapping("/updSendBills{viewName}")
	public ModelAndView updSendBills(HttpServletRequest request, HttpServletResponse response, SendBills po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		MyRequest req = new MyRequest(request);
		if ("1".equals(viewName))
		{
			Long id = req.getLong("keyIndex");
			po = service.getById(id);
			result = new ModelAndView();
			Map map = new HashMap();
			List departList = departmentsService.getList(map);//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			List<Customs> customCodes= customsService.getList(map );
			List personList = personService.getList(map);  //人员信息
			List vehicleList = vehicleService.getList(map); //车辆信息
			result.addObject("personList",personList);
			result.addObject("vehicleList",vehicleList);
			result.addObject("customCodes", customCodes);
			result.addObject("departList", departList);
			result.addObject("deportList", deportList);
			result.addObject("po", po);
			List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.SENDBILL_GOODS.getValue(), new Integer(String.valueOf(id)));
			result.addObject("refGoods", refGoods);
			result.setViewName("/manage/warehouse/updSendBills.jsp");
		}
		else if ("2".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			String goodsInfo = req.getString("goodsInfo");
			try
			{
				List<RefGoods> refOldGoods = refGoodsService.getByInfoType(RefGoodsType.SENDBILL_GOODS.getValue(),po.getId() );
				service.update(po);
				processRefGoods(request, RefGoodsType.SENDBILL_GOODS, po.getId(), goodsInfo);
				//处理库存量数量
				List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.SENDBILL_GOODS.getValue(),po.getId() );

				calcGoodsStock(refOldGoods, refGoods, surplusOrderService, po.getDepot_code(), po.getAuthCoCode(), false, true);
				
				writer.write("修改发货单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("修改发货单失败！" + e.getCause());
			}
		}
		return result;
	}

	//获得分页
	@RequestMapping("/getSendBills")
	public ModelAndView getSendBills(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="page", defaultValue="1")int page)
	{
		int pageSize = 10;
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		//只查询当前用户所属部门
		map.put("authCoCode", UserShare.getCurrentUserCoCode(request));
		//map.put("authDepCode", UserShare.getCurrentUserDepCode(request));
		PageModel<SendBills> pageModel = service.getPage(page, pageSize, map);
		for(int i=0;i<pageModel.getResult().size();i++){
			String code = pageModel.getResult().get(i).getCustom_code();
			pageModel.getResult().get(i).setCustoms_name(customsService.getCustomName(false, 0, code));
		}
		ModelAndView result = new ModelAndView();
		PageNav pageNav = new PageNav(request, pageModel);
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		Map custMap = new HashMap();
		List customsList = customsService.getList(custMap);// 客户信息
		result.addObject("customsList", customsList);
		result.setViewName("/manage/warehouse/getSendBills.jsp");
		return result;
	}
	
	//获得审核通过并且未复制的数据
	@RequestMapping("/getCopyDelivery")
	public ModelAndView getDelivery(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="page", defaultValue="1")int page)
	{
		int pageSize = 10;
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		//只查询当前用户所属公司及部门
		map.put("authCoCode", UserShare.getCurrentUserCoCode(request));
		//map.put("authDepCode", UserShare.getCurrentUserDepCode(request));
		map.put("copy_status", 0);
		PageModel<Delivery> pageModel = deliveryService.getPage(page, pageSize, map);
		ModelAndView result = new ModelAndView();
		PageNav pageNav = new PageNav(request, pageModel);
		Map nullMap = new HashMap();
		List personList = personService.getList(nullMap);  //人员信息
		List vehicleList = vehicleService.getList(nullMap); //车辆信息
		result.addObject("personList",personList);
		result.addObject("vehicleList",vehicleList);
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		result.addObject("co_code", UserShare.getCurrentUserCoCode(request)+"["+UserShare.getCurrentUserCoName(request)+"]");
		result.setViewName("/manage/warehouse/getCopyDelivery.jsp");
		return result;
	}
	
	//复制送货单数据
	@RequestMapping("/copyDelivery")
	public void copyData(HttpServletRequest request,HttpServletResponse response) throws Exception {
		MyRequest req = new MyRequest(request);
		Date send_date = req.getDate("send_date");
		Integer send_type = req.getInt("send_type");
		String shipper_code = req.getString("shipper_code");
		String license_plate = req.getString("license_plate");
		String driver_code = req.getString("driver_code");
		String car_user = req.getString("car_user");
		Date delivery_date = req.getDate("delivery_date");
		
		Long[] idArry = CollectionUtil.toLongArray(req.getLongArray("keyIndex", 0));
		for (int i = 0; i < idArry.length; i++) {
			Long id = req.getLong("keyIndex");
			Delivery delivery = deliveryService.getById(id);
			delivery.setCopy_status(1);
			deliveryService.update(delivery);
			SendBills sendBill = new SendBills();
			
			sendBill.setSend_date(send_date);
			sendBill.setSend_type(send_type);
			sendBill.setShipper_code(shipper_code);
			sendBill.setLicense_plate(license_plate);
			sendBill.setDriver_code(driver_code);
			sendBill.setCar_user(car_user);
			sendBill.setDelivery_date(delivery_date);
			
			sendBill.setSend_sn(service.getNewSendSn());
			sendBill.setCustom_code(delivery.getCustom_code());
			sendBill.setOrder_id(delivery.getOrder_id());
			sendBill.setOrder_sn(delivery.getOrder_code());
			
			sendBill.setAuthCoCode(UserShare.getCurrentUserCoCode(request));//所属公司代码
			//sendBill.setAuthDepCode(UserShare.getCurrentUserDepCode(request));//所属部门代码
			sendBill.setAcc_period(delivery.getAcc_period());//复制财务核算期
			
			//复制仓库代码
			sendBill.setDepot_code(delivery.getDepot_code());
			sendBill.setDepot_id(delivery.getDepot_id());
			
			service.add(sendBill);
			
			List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.DELIVERIE_GOODS.getValue(), delivery.getId());
			for (RefGoods refGoods2 : refGoods) {
				refGoods2.setInfo_id(sendBill.getId());
				refGoods2.setInfo_type(RefGoodsType.SENDBILL_GOODS.getValue());
				refGoodsService.add(refGoods2);
				//减少库存
				surplusOrderService.addStockAmount(refGoods2.getGoods_id(), sendBill.getDepot_code(), sendBill.getAuthCoCode(), -refGoods2.getAmount(), true);
				//减少下单数
				surplusOrderService.addDownOrderAmount(refGoods2.getGoods_id(), sendBill.getDepot_code(), sendBill.getAuthCoCode(), -refGoods2.getAmount(), true);
			}
		}
	}
	
	

	//明细
	@RequestMapping("/getSendBillsById")
	public ModelAndView getSendBillsById(HttpServletRequest request, HttpServletResponse response)
	{
		SendBills po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		po.setCustoms_name(customsService.getCustomName(false, 0, po.getCustom_code()));
		ModelAndView result = new ModelAndView();
		result.addObject("po", po);
		result.addObject("dep", departmentsService.getByCode(po.getSell_dep_code()));
		result.addObject("depot", depotsService.getByCode(po.getDepot_code()));
		result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.SENDBILL_GOODS.getValue(),new Integer(String.valueOf(id)) ));
		result.setViewName("/manage/warehouse/getSendBillsById.jsp");
		return result;
	}
	
	
	//审核
	@RequestMapping("/audit{viewName}")
	public ModelAndView audit(HttpServletRequest request, HttpServletResponse response,@PathVariable String viewName)throws IOException
	{
		ModelAndView result = null;;
		SendBills po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		if ("1".equals(viewName))
		{
			result = new ModelAndView();
			result.addObject("po", po);
			result.addObject("audit", "audit");
			result.addObject("dep", departmentsService.getByCode(po.getSell_dep_code()));
			result.addObject("depot", depotsService.getByCode(po.getDepot_code()));
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.SENDBILL_GOODS.getValue(),new Integer(String.valueOf(id)) ));
			result.setViewName("/manage/warehouse/getSendBillsById.jsp");
			
		}else if ("2".equals(viewName)) {
			PrintWriter writer = response.getWriter();
			try
			{
				//审核人员ID
				//审核人员代码
				//审核状态
				po.setAudit_status(1);
				service.update(po);
				
				this.Bookkeeping(po);
				writer.write("审核成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("审核失败！" + e.getCause());
			}
		}
		return result;
	}
	
	
	//记账
	/*@RequestMapping("/acc{viewName}")
	public ModelAndView acc(HttpServletRequest request, HttpServletResponse response,@PathVariable String viewName)throws IOException
	{
		ModelAndView result = null;
		SendBills po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		if ("1".equals(viewName))
		{
			result = new ModelAndView();
			result.addObject("acc","acc");
			result.addObject("po", po);
			result.setViewName("/manage/warehouse/getSendBillsById.jsp");
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.SENDBILL_GOODS.getValue(),new Integer(String.valueOf(id)) ));
			
		}else if ("2".equals(viewName)) {
			PrintWriter writer = response.getWriter();
			try
			{
				//添加数据到仓库帐中
				po.setAcc_status(1);
				service.update(po);
				
				List<RefGoods> refgoodList = refGoodsService.getByInfoType(RefGoodsType.SENDBILL_GOODS.getValue(), po.getId());
				if (refgoodList!=null && refgoodList.size()!=0) {
					for (int i = 0; i < refgoodList.size(); i++) {
						*//**
						 * 减少库存数量
						 *//*
						RefGoods refGoods = (RefGoods)refgoodList.get(i);
						Goods goods = goodsService.getById(new Long(refGoods.getGoods_id()));
						//更新库存数量
						double stock = goods.getStock()-refGoods.getAmount();
						goods.setStock(stock);
						goodsService.update(goods);
						*//**
						 * 记录到仓库帐中
						 *//*
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						WarehouseAccounts warehouseAccounts = new WarehouseAccounts();
						warehouseAccounts.setAcc_period(po.getAcc_period());//财务统计核算期
						warehouseAccounts.setInfo_type("发货单");//仓库帐类型
						warehouseAccounts.setGoods_sn(goods.getGoods_sn());//物料代码
						warehouseAccounts.setDep_code(po.getDepot_code());//仓库代码
						warehouseAccounts.setCreate_date(po.getSend_date());//入仓单日期
						warehouseAccounts.setCreate_time(po.getSend_time());//入仓库时间
						warehouseAccounts.setSys_date(format.format(new Date()));//生成仓库帐时间
						warehouseAccounts.setAmount(refGoods.getAmount());//物品数量
						warehouseAccounts.setStock_num(stock);//当前库存数量
						warehouseAccounts.setSend_amount(0);//已下采购单要求送货数量, 根据采购单号 查询采购数量
						String remark = "单号："+po.getSend_sn()+"，部门："+po.getSell_dep_code()+"";
						warehouseAccounts.setRemark(remark);//凭证号（单号）、部门、客户等>
						warehouseAccountsService.add(warehouseAccounts);
					}
				}
				
				
				writer.write("记账成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("记账失败！" + e.getCause());
			}
		}
		return result;
	}*/
	 
	/**
	 *记账
	 */
	private void Bookkeeping(SendBills po){
		calcWarehouseAccount(warehouseAccountsService, RefGoodsType.SENDBILL_GOODS, po.getId(), po.getDepot_code(), po.getAuthCoCode(), false);
	}
	
	
}
